<?php  
class ControllerProductProduct extends FrontController {

	public function index() { 
		global $CATEGORIES, $CATEGORY;
		
		M('catalog/product');
		$product_info = null;
		$product_id = (int) G('product_id', 0);
		if ($product_id) $product_info = $this->model_catalog_product->getProduct($product_id);
		
		if (!$product_info) {
			return $this->forward('error/not_found');
		}
		
		if (isset($CATEGORIES[$product_info['category_id']])) {
			$CATEGORY = $CATEGORIES[$product_info['category_id']];
		}
		if ($CATEGORY) {
			foreach (explode(',', $CATEGORY['path']) as $category_id) {
				$this->data['breadcrumbs'][] = array(
					'text'      => $CATEGORIES[$category_id]['name'],
					'href'      => $CATEGORIES[$category_id]['link'],
					'separator' => $this->_['text_separator']
				);
			}
		}	

		$this->document->setTitle(!empty($product_info['seo_title']) ? $product_info['seo_title'] : $product_info['name']);
		$this->document->setDescription($product_info['meta_description']);
		$this->document->setKeywords($product_info['meta_keyword']);
		$this->document->addLink(HTTP_SERVER . $product_info['link'], 'canonical');
		$this->document->setOpenGraph('og:title', $product_info['name']);
		$this->document->setOpenGraph('og:type', 'product');
		$this->document->setOpenGraph('og:site_name', C('config_name'));
		$this->document->setOpenGraph('og:image', HTTP_SERVER . 'image/' . $product_info['image']);
		$this->document->setOpenGraph('og:url', HTTP_SERVER . $product_info['link']);
		$this->document->setOpenGraph('og:description', $product_info['meta_description']);
		$this->document->setOpenGraph('fb:app_id', C('config_fb_appid'));

		$this->data['heading_title'] = $product_info['name'];			

		$this->data['product_id'] = $product_id;
		$this->data['manufacturer'] = $product_info['manufacturer'];
		$this->data['manufacturers'] = U('product/manufacturer/info/', 'manufacturer_id=' . $product_info['manufacturer_id']);
		$this->data['model'] = $product_info['model'];
		$this->data['reward'] = $product_info['reward'];
		$this->data['points'] = $product_info['points'];
		$this->data['text_promotion'] = '';
		
		$stock_statuses = C('cache_stock_status');
		if (isset($stock_statuses[$product_info['stock_status_id']])) {
			$product_info['stock_status'] = $stock_statuses[$product_info['stock_status_id']];
		}
		
		$weight_classes = C('cache_weight_class');
		if (isset($weight_classes[$product_info['weight_class_id']])) {
			$product_info['weight_class'] = $weight_classes[$product_info['weight_class_id']]['unit'];
		}
		
		$length_classes = C('cache_length_class');
		if (isset($length_classes[$product_info['length_class_id']])) {
			$product_info['length_class'] = $length_classes[$product_info['length_class_id']]['unit'];
		}
		
		if ($product_info['quantity'] <= 0) {
			$this->data['stock'] = $product_info['stock_status'];
		} elseif (C('config_stock_display')) {
			$this->data['stock'] = $product_info['quantity'];
		} else {
			$this->data['stock'] = $this->_['text_instock'];
		}
		
		if ($product_info['image']) {
			$this->data['popup'] = thumb($product_info['image'], C('config_image_popup_width'), C('config_image_popup_height'));
		} else {
			$this->data['popup'] = '';
		}
		
		if ($product_info['image']) {
			$this->data['thumb'] = thumb($product_info['image'], C('config_image_thumb_width'), C('config_image_thumb_height'));
		} else {
			$this->data['thumb'] = '';
		}
		
		$this->data['images'] = array();
		
		if ($product_info['image']) {
			$this->data['images'][] = array(
				'popup' => thumb($product_info['image'], C('config_image_popup_width'), C('config_image_popup_height')),
				'thumb' => thumb($product_info['image'], C('config_image_thumb_width'), C('config_image_thumb_height')),
				'small' => thumb($product_info['image'], C('config_image_additional_width'), C('config_image_additional_height'))
			);
		}
		
		$results = $this->model_catalog_product->getProductImages($product_id);
		
		foreach ($results as $result) {
			$this->data['images'][] = array(
				'popup' => thumb($result['image'], C('config_image_popup_width'), C('config_image_popup_height')),
				'thumb' => thumb($result['image'], C('config_image_thumb_width'), C('config_image_thumb_height')),
				'small' => thumb($result['image'], C('config_image_additional_width'), C('config_image_additional_height'))
			);
		}	

		$this->data['price'] = pprintf($product_info['price'], $product_info['tax_class_id']);
		$this->data['special'] = 0;
		
		if ($product_info['special']) {
			$this->data['special'] = $product_info['special'];
			if ($product_info['special_date_end'] != '0000-00-00') {
				$this->data['text_promotion'] = sprintf($this->_['text_special_2'], v5_date_sub($product_info['special_date_end'], $GLOBALS['V5_DATE']));
			}
			else {
				$this->data['text_promotion'] =  $this->_['text_special_1'];
			}
		}
		elseif ($product_info['discount']) {
			$this->data['special'] = $product_info['discount'];
			$this->data['text_promotion'] = sprintf($this->_['text_discount_2'],
					round(($product_info['price'] - $product_info['discount']) * 100 / $product_info['price']  , 1));
		}

		$this->data['special'] = pprintf($this->data['special'], $product_info['tax_class_id']);

		$this->data['tax'] = C('config_tax') ? currency((float)$product_info['special'] ? $product_info['special'] : $product_info['price']) : false;
		
		$this->data['discounts'] = array(); 
		if (!$product_info['special']) {
			$discounts = $this->model_catalog_product->getProductDiscounts($product_id, $product_info['price']);
			
			foreach ($discounts as $discount) {
				if ($discount['quantity'] == 1) continue;
				$this->data['discounts'][] = array(
					'quantity' => $discount['quantity'],
					'price'    => pprintf($discount['price'], $product_info['tax_class_id'])
				);
			}
		}
		
		$this->data['currency_code'] = $this->currency->getCode();
		
		$this->data['options'] = array();
		
		foreach ($this->model_catalog_product->getProductOptions($product_id) as $option) { 
			if ($option['type'] == 'select' || $option['type'] == 'radio' || $option['type'] == 'checkbox' || $option['type'] == 'image') { 
				$option_value_data = array();
				
				foreach ($option['option_value'] as $option_value) {
					if (!$option_value['subtract'] || ($option_value['quantity'] > 0)) {
						$option_value_data[] = array(
							'product_option_value_id' => $option_value['product_option_value_id'],
							'option_value_id'         => $option_value['option_value_id'],
							'name'                    => $option_value['name'],
							'image'                   => thumb($option_value['image'], 50, 50),
							'price'                   => pprintf($option_value['price'], $product_info['tax_class_id']),
							'price_prefix'            => $option_value['price_prefix']
						);
					}
				}
				
				$this->data['options'][] = array(
					'product_option_id' => $option['product_option_id'],
					'option_id'         => $option['option_id'],
					'name'              => $option['name'],
					'type'              => $option['type'],
					'option_value'      => $option_value_data,
					'required'          => $option['required']
				);					
			} elseif ($option['type'] == 'text' || $option['type'] == 'textarea' || $option['type'] == 'file' || $option['type'] == 'date' || $option['type'] == 'datetime' || $option['type'] == 'time') {
				$this->data['options'][] = array(
					'product_option_id' => $option['product_option_id'],
					'option_id'         => $option['option_id'],
					'name'              => $option['name'],
					'type'              => $option['type'],
					'option_value'      => $option['option_value'],
					'required'          => $option['required']
				);						
			}
		}
						
		if ($product_info['minimum']) {
			$this->data['minimum'] = $product_info['minimum'];
		} else {
			$this->data['minimum'] = 1;
		}
		$this->data['text_minimum'] = sprintf($this->_['text_minimum'], $product_info['minimum']);
		$this->data['text_reviews'] = sprintf($this->_['text_reviews'], $product_info['reviews']);
		$this->data['reviews'] = $product_info['reviews'];
		$this->data['rating'] = (int)$product_info['rating'];
		$this->data['description'] = v5_html_entity_decode($product_info['description']);
		$this->data['attribute_groups'] = $this->model_catalog_product->getProductAttributes($product_id);
		
		//related products
		$this->data['products'] = array();		
		$results = $this->model_catalog_product->getProductRelated($product_id);
		
		foreach ($results as $result) {
			$this->data['products'][] = array(
				'product_id' => $result['product_id'],
				'thumb'   	 => thumb($result['image'], C('config_image_related_width'), C('config_image_related_height')),
				'name'    	 => $result['name'],
				'price'       => pprintf($result['price'], $result['tax_class_id']),
				'special'     => pprintf($result['special'], $result['tax_class_id']),
				'rating'     => C('config_review_status') ? $result['rating'] : false,
				'reviews'    => sprintf($this->_['text_reviews'], (int)$result['reviews']),
				'href'    	 => $result['link'],
			);
		}	
		
		//gifts
		$this->data['gifts'] = array();
		$results = $this->model_catalog_product->getProductGifts($product_id);
		foreach ($results as $result) {
			$this->data['gifts'][] = array(
				'thumb'   	 => thumb($result['image'], C('config_image_additional_width'), C('config_image_additional_height')),
				'name'    	 => $result['name'],
				'href'    	 => $result['link'],
				'qty'        => $result['qty']
			);
		}

		$this->data['packages'] = array();
		$results = $this->model_catalog_product->getProductPackages($product_id);
		foreach ($results as $result) {
			$this->data['packages'][] = array(
				'product_package_id' => $result['product_package_id'],
				'thumb'   	 => thumb($result['image'], C('config_image_thumb_width'), C('config_image_thumb_height')),
				'name'    	 => $result['name'],
				'href'    	 => $result['link'],
				'special'    => ($result['org_price'] > $result['price']) ? pprintf($result['price'], $result['tax_class_id']) : 0,
				'price'  	 => ($result['org_price'] > $result['price']) ? pprintf($result['org_price'], $result['tax_class_id']) : pprintf($result['price'], $result['tax_class_id']),
				'product_id' => $result['related_id']
			);
		}

		$this->data['tags'] = array();

		if ($product_info['tag']) {
			$tags = explode(',', trim($product_info['tag'], ','));
			
			foreach ($tags as $tag) {
				$this->data['tags'][] = array(
					'tag'  => trim($tag),
					'href' => U('product/search', 'search=' . trim($tag))
				);
			}
		}
		$this->model_catalog_product->updateViewed($product_id);
		
		$template = empty($product_info['template']) ? 'product.tpl' : $product_info['template'];
		$this->display("product/$template");
  	}
	
	public function review() {
    	$this->language->load('product/product');
		
		$this->data['text_on'] = $this->_['text_on'];
		$this->data['text_no_reviews'] = $this->_['text_no_reviews'];
		
		M('catalog/review');
		
		$page = (int) $this->request->get('page', 1);
		$product_id = (int) $this->request->get('product_id', 0);
		
		$this->data['reviews'] = array();
		
		$review_total = $this->model_catalog_review->getTotalReviewsByProductId($product_id);
			
		$results = $this->model_catalog_review->getReviewsByProductId($product_id, ($page - 1) * 10, 10);
      		
		foreach ($results as $result) {
        	$this->data['reviews'][] = array(
        		'author'     => $result['author'],
				'text'       => $result['text'],
				'rating'     => (int)$result['rating'],
        		'reviews'    => sprintf($this->_['text_reviews'], (int)$review_total),
        		'date_added' => date($this->_['date_format_short'], strtotime($result['date_added']))
        	);
      	}			
			
		$pagination = new Pagination();
		$pagination->total = $review_total;
		$pagination->page = $page;
		$pagination->limit = 10; 
		$pagination->text = $this->_['text_pagination'];
		$pagination->url = U('product/product/review', "product_id=$product_id" . '&page={page}');
			
		$this->data['pagination'] = $pagination->render();
		
		$this->display('product/review.tpl', false);
	}
	
	public function write() {
		$this->language->load('product/product');
		
		M('catalog/review');
		
		$json = array();
		
		if ($this->request->server['REQUEST_METHOD'] == 'POST') {
			if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 25)) {
				$json['error'] = $this->_['error_name'];
			}
			if ($this->request->post['email'] && !preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $this->request->post['email'])) {
				$json['error'] = $this->_['error_email'];
			}		
			if ((utf8_strlen($this->request->post['text']) < 25) || (utf8_strlen($this->request->post['text']) > 1000)) {
				$json['error'] = $this->_['error_text'];
			}
	
			if (empty($this->request->post['rating'])) {
				$json['error'] = $this->_['error_rating'];
			}
	
			if (empty($this->session->data['captcha']) || ($this->session->data['captcha'] != $this->request->post['captcha'])) {
				$json['error'] = $this->_['error_captcha'];
			}
				
			if (!isset($json['error'])) {
				unset($this->session->data['captcha']);
				$this->model_catalog_review->addReview($this->request->get['product_id'], $this->request->post);
				$json['success'] = $this->_['text_success'];
			}
		}
		
		$this->response->setOutput(json_encode($json));
	}
	
	public function faq() {
		$this->language->load('product/product');
	
		$this->data['text_on'] = $this->_['text_on'];

		M('catalog/faq');
	
		$page = (int) $this->request->get('page', 1);
		$product_id = (int) $this->request->get('product_id', 0);
	
		$this->data['faqs'] = array();
	
		$faq_total = $this->model_catalog_faq->getTotalFaqsByProductId($product_id);
			
		$results = $this->model_catalog_faq->getFaqsByProductId($product_id, ($page - 1) * 10, 10);
	
		foreach ($results as $result) {
			$this->data['faqs'][] = array(
					'author'     => $result['author'],
					'question'   => $result['question'],
					'answer'     => $result['answer'],
					'date_added' => v5_date_format($result['date_added'])
			);
		}
			
		$pagination = new Pagination();
		$pagination->total = $faq_total;
		$pagination->page = $page;
		$pagination->limit = 10;
		$pagination->text = $this->_['text_pagination'];
		$pagination->url = U('product/product/faq', "product_id=$product_id" . '&page={page}');
			
		$this->data['pagination'] = $pagination->render();
	
		$this->display('product/faq.tpl', false);
	}
	
	public function writefaq() {
		$this->language->load('product/product');
	
		M('catalog/faq');
	
		$json = array();
	
		if ($this->request->isPost()) {
			if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 25)) {
				$json['error'] = $this->_['error_name'];
			}
			if ($this->request->post['email'] && !preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $this->request->post['email'])) {
				$json['error'] = $this->_['error_email'];
			}
			if ((utf8_strlen($this->request->post['question']) < 25) || (utf8_strlen($this->request->post['question']) > 1000)) {
				$json['error'] = $this->_['error_text'];
			}
	
			if (empty($this->session->data['captcha']) || ($this->session->data['captcha'] != $this->request->post['captcha'])) {
				$json['error'] = $this->_['error_captcha'];
			}
	
			if (!isset($json['error'])) {
				$this->model_catalog_faq->addFaq($this->request->get['product_id'], $this->request->post);
				unset($this->session->data['captcha']);
				$json['success'] = $this->_['text_success'];
			}
		}
	
		$this->response->setOutput(json_encode($json));
	}
	
	public function captcha() {
		$this->load->library('captcha');
		
		$captcha = new Captcha();
		
		$this->session->data['captcha'] = $captcha->getCode();
		
		$captcha->showImage();
	}
	
	public function upload() {
		$this->language->load('product/product');
		
		$json = array();
		
		if (!empty($this->request->files['file']['name'])) {
			$filename = basename(preg_replace('/[^a-zA-Z0-9\.\-\s+]/', '', html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8')));
			
			if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 64)) {
        		$json['error'] = $this->_['error_filename'];
	  		}	  	
			
			// Allowed file extension types
			$allowed = array();
			
			$filetypes = explode(",", C('config_file_extension_allowed'));
			
			foreach ($filetypes as $filetype) {
				$allowed[] = trim($filetype);
			}
			
			if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
				$json['error'] = $this->_['error_filetype'];
       		}	
			
			// Allowed file mime types		
		    $allowed = array();
			
			$filetypes = explode("\n", C('config_file_mime_allowed'));
			
			foreach ($filetypes as $filetype) {
				$allowed[] = trim($filetype);
			}
			
			if (!in_array($this->request->files['file']['type'], $allowed)) {
				$json['error'] = $this->_['error_filetype'];
			}
			
			if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
				$json['error'] = $this->_['error_upload_' . $this->request->files['file']['error']];
			}
		} else {
			$json['error'] = $this->_['error_upload'];
		}
		
		if (!$json && is_uploaded_file($this->request->files['file']['tmp_name']) && file_exists($this->request->files['file']['tmp_name'])) {
			$file = basename($filename) . '.' . md5(mt_rand());
			
			// Hide the uploaded file name so people can not link to it directly.
			$json['file'] = $this->encryption->encrypt($file);
			
			move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $file);
			
			$json['success'] = $this->_['text_upload'];
		}	
		
		$this->response->setOutput(json_encode($json));		
	}
}
?>